package deployr.core;

import java.io.*;

public class Scan {

	private final File root;

	public Scan(ScanListener listener, File root) {
		this.root = root;
		find(listener, root);
	}

	private boolean allowedDirectory(File fileOrDirectory) {
		if (!fileOrDirectory.isDirectory()) return false;
		if (fileOrDirectory.getName().matches("^.svn")) return false;
		return true;
	}

	private boolean allowedFile(File fileOrDirectory) {
		return fileOrDirectory.isFile();
	}

	private void continueDiscoverDirectory(ScanListener listener, File fileOrDirectory) {
		for (File anotherFileOrDirectory : fileOrDirectory.listFiles()) {
			find(listener, anotherFileOrDirectory);
		}
	}

	private void continueDiscoverFile(ScanListener listener, File fileOrDirectory) {
		listener.discovered(root, relativePathTo(fileOrDirectory));
	}

	private void discoverDirectory(ScanListener listener, File fileOrDirectory) {
		if (allowedDirectory(fileOrDirectory)) {
			continueDiscoverDirectory(listener, fileOrDirectory);
		}
	}

	private void discoverFile(ScanListener listener, File fileOrDirectory) {
		if (allowedFile(fileOrDirectory)) {
			continueDiscoverFile(listener, fileOrDirectory);
		}
	}

	private void find(ScanListener listener, File fileOrDirectory) {
		discoverFile(listener, fileOrDirectory);
		discoverDirectory(listener, fileOrDirectory);
	}

	private File relativePathTo(File fileOrDirectory) {
		return new File(fileOrDirectory.getAbsolutePath().replaceAll(root.getAbsolutePath(), ""));
	}
}
